home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / pluginy Firefox / 2888 / 2888.xpi / components / nsIGMarksCom_google.js next >
Text File  |  2009-12-16  |  33KB  |  874 lines

  1. var GMARKS_COM_CONTRACTID = "@mozilla.org/gmarks/com/google;1";
  2. var GMARKS_COM_CID = Components.ID('{f6c06be0-b631-11db-abbd-0800200c9a66}');
  3. var GMARKS_COM_IID = Components.interfaces.nsIGMarksCom;
  4. function nsGMarksCom(){
  5.   this.wrappedJSObject = this;
  6. }
  7. nsGMarksCom.prototype = {
  8.   GMS: null,
  9.   passLoc: "chrome://gmarks",
  10.   signature: "",
  11.   OLD_BKMKLET_URL: "gmarksbookmarklet.com",
  12.   BKMKLET_URL: "https://www.google.com/bookmarks/find?q=javascript&src=gmarksbkmklet",
  13.   get manageOnlineURL(){
  14.     return "https://www.google.com/bookmarks/";
  15.   },
  16.   setGMS: function(nsGMarksService){
  17.     this.GMS=nsGMarksService;
  18.   },
  19.   onRemoveBookmark : function(bkmk) {
  20.     //dump("com.removebookmark: "+bkmk.url+"|"+bkmk.id+"\n");
  21.     this.send('dlq='+bkmk.id,true,bkmk);
  22.   },
  23.   onRenameLabel: function(oldLabel,newLabel){
  24.     this.send('op=modlabel&labels='+encodeURIComponent(oldLabel+','+newLabel),true);
  25.   },
  26.   onRemoveLabel: function(rlabel){
  27.     this.send('op=modlabel&labels='+encodeURIComponent(rlabel));
  28.   },
  29.   //the bookmark already has the labels added to it
  30.   //Labels is an array of labels
  31.   onAddLabelsToBookmark: function(bm,Labels){
  32.     this.sendUpdateBookmark(bm);
  33.   },
  34.   //bm already has had the label removed
  35.   onRemoveLabelFromBookmark: function(bm,aLabel){
  36.     this.sendUpdateBookmark(bm);
  37.   },
  38.   //once again, bm has already been modified
  39.   onRenameBookmark: function(bm, newTitle){
  40.     this.sendUpdateBookmark(bm);
  41.   },
  42.   sendUpdateBookmark: function(bm,async){
  43.     //var data='q='+encodeURIComponent(bm.url)+'&title='+encodeURIComponent(bm.title)
  44.     //  +'&labels='+bm.labels+'&annotation='+bm.notes;
  45.     var data=this.getSendData(bm);
  46.     this.send(data,async,bm);
  47.   },
  48.   updateMultipleBookmarks: function(bkmks,i, time,tries){
  49.     var com=this;
  50.     if (!time){
  51.       var d=new Date();
  52.       time=d.valueOf();
  53.     }
  54.     if (!tries) tries=0;
  55.     if (i<bkmks.length){
  56.       var bm=bkmks[i];
  57.       var req = this.getSendRequest();
  58.       req.send(this.getSendData(bm));
  59.       debug("Send update request for: "+bm.title+"\n");
  60.       req.onreadystatechange = function(ev) {
  61.         if(req.readyState == 4) {
  62.           var status = -1;
  63.           try {
  64.             status = req.status;
  65.           }
  66.           catch(e) {
  67.             dump("Request failed, could not get status info\n");
  68.           }
  69.           if(status == 200){
  70.             if (req.responseText && req.responseText.length>1000)
  71.               com.GMS.errorSendingBookmark(bm);
  72.             else
  73.               com.updateMultipleBookmarks(bkmks,i+1, time,0);
  74.           }
  75.           else{//Doesn't work
  76.             tries++;
  77.             if (tries<5){//Try it several of times
  78.               com.updateMultipleBookmarks(bkmks,i,time,tries);
  79.             }
  80.             else{
  81.               //Error...alert user
  82.               com.GMS.errorSendingBookmark(bm);
  83.             }
  84.           }
  85.         }
  86.       }
  87.     }
  88.     else{
  89.       this.getIDs(i,time,bkmks);
  90.     }
  91.   },
  92.   getSignOffRequest: function(){
  93.     var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
  94.            .createInstance(Components.interfaces.nsIXMLHttpRequest);
  95.     req.open("GET","https://www.google.com/accounts/Logout2",true);
  96.     return req;
  97.   },
  98.   //Used with filters, exporting, and other things
  99.   getSendRequest: function(bm){
  100.     var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
  101.            .createInstance(Components.interfaces.nsIXMLHttpRequest);
  102.     req.open("POST", 'https://www.google.com/bookmarks/mark', true);
  103.     req.setRequestHeader("Content-Type",
  104.       "application/x-www-form-urlencoded");
  105.     var http=Components.classes["@mozilla.org/network/protocol;1?name=http"].getService(Components.interfaces.nsIHttpProtocolHandler);
  106.     var useragent=http.userAgent;
  107.     //req.setRequestHeader('User-Agent', useragent+" GoogleToolbarFF");
  108.     req.setRequestHeader('User-Agent', useragent+" GMarks");
  109.     req.setRequestHeader('Accept','text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5');
  110.     return req;
  111.   },
  112.   getSendData: function(bm){
  113.     /*
  114.      * Google removes javascript bookmarklets from the rss feed,
  115.      * so we need to move the javascript to the notes field
  116.      */
  117.     if (bm.url.indexOf("javascript:")==0){
  118.       bm.notes=bm.url;
  119.       bm.url=this.BKMKLET_URL+"&str=";
  120.       /* add a random string to make a unique url */
  121.       var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz".split("");
  122.       var string_length=40;
  123.       for (var i=0; i<string_length; i++) {
  124.         var idx = Math.floor(Math.random() * chars.length);
  125.         bm.url += chars[idx];//chars.substring(rnum,rnum+1);
  126.       }
  127.     }
  128.     var data='s='+this.signature+'&bkmk='+encodeURIComponent(bm.url)+'&title='+encodeURIComponent(bm.title)+
  129.       '&labels='+encodeURIComponent(bm.labels)+'&annotation='+encodeURIComponent(bm.notes)+"&zx="+Math.floor(Math.random()*32768);
  130.     return data;
  131.   },
  132.   getRemoveRequest: function(){
  133.     return this.getSendRequest();
  134.   },
  135.   getRemoveData: function(bm){
  136.     return 'dlq='+bm.id+'&s='+this.signature;
  137.   },
  138.   //sends the data to Google
  139.   send: function(data,async,bm,tries){
  140.     async=async!=null?async:true;
  141.     var req = this.getSendRequest();
  142.     if (data && data.length>0) {
  143.         /* Add Signature */
  144.         data+='&s='+this.signature;
  145.     }
  146.     req.send(data);
  147.     var com=this;
  148.     req.onreadystatechange = function() {
  149.       if(req.readyState == 4) {
  150.         var status = -1;
  151.         try {
  152.           status = req.status;
  153.         }
  154.         catch(e) {
  155.           debug("error getting status after sending\n",true);
  156.         }
  157.         if(status == 200){
  158.           if (bm){
  159.             if (bm.id==0){
  160.               com.getIDs(1,bm.date);
  161.               //com.getID(bm); //so it can be deleted later...
  162.             }
  163.           }
  164.         }
  165.         else{
  166.           if (!tries) tries=1; else tries++;
  167.           if (tries<5){
  168.             com.send(data,async,bm,tries);
  169.           }
  170.           else{
  171.             //Error...alert user
  172.             com.GMS.errorSendingBookmark(bm);
  173.           }
  174.         }
  175.       }
  176.     }
  177.   },
  178.   checkSignedCookie: function(){
  179.     var cookieManager = Components.classes["@mozilla.org/cookiemanager;1"]
  180.               .getService(Components.interfaces.nsICookieManager);
  181.     var i = cookieManager.enumerator;
  182.     var signedIn=false;
  183.  
  184.     while (i.hasMoreElements()){
  185.       var cookie = i.getNext();
  186.       if (cookie instanceof Components.interfaces.nsICookie){
  187.         if (cookie.host == ".google.com")
  188.           if (cookie.name == "SID" || cookie.name == "LSID"){
  189.             return true;
  190.           }
  191.       }
  192.     }
  193.     return false;
  194.   },
  195.   onSignIn: function(refresh,email,pass,action,sidebar,start,num,token) {
  196.     var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
  197.       .createInstance(Components.interfaces.nsIXMLHttpRequest);
  198.     req.open("POST", 'https://www.google.com/accounts/ServiceLoginAuth', true);
  199.     req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  200.     var data="ltmpl=wsad<mplcache=2&rm=false&Email="+email+"&Passwd="+pass;
  201.     if (token && token!="")
  202.       data+=token;
  203.     req.setRequestHeader('Content-Length', data.length);
  204.     req.send(data);
  205.     var com=this;
  206.     req.onreadystatechange = function(ev){
  207.       if(req.readyState == 4){
  208.         var status = -1;
  209.         try {status = req.status;}catch(e) {}
  210.         if(status == 200){
  211.           com.GMS.isSignedIn = com.checkSignedCookie();
  212.           if (com.GMS.isSignedIn && refresh )
  213.             com.GMS.doCommand("retryreload");
  214.           else if (com.GMS.isSignedIn){
  215.             com.GMS.doCommand("bookmarks-load-start");
  216.             com.GMS.getBookmarksFeed(action,sidebar,start,num);
  217.           } else if (!token || token==""){
  218.             var cookies = req.getResponseHeader("Set-Cookie").split(/;|(\n)/);
  219.             for (var i=0;i<cookies.length;i++){
  220.               if (cookies[i].match(/^(GALX)=/)){
  221.                 token="&"+cookies[i];
  222.               }
  223.             }
  224.             if (token && token!="")
  225.               com.onSignIn(refresh,email,pass,action,sidebar,start,num,token);
  226.           }
  227.           else{
  228.             com.GMS.recievedBookmarks=0;
  229.             com.GMS.doCommand('onrefresh');
  230.           }
  231.         }
  232.         
  233.       }
  234.     }
  235.   },
  236.   signOut: function(){
  237.  
  238.   },
  239.   /*
  240.    * Converts the date from a string into a date object
  241.    */
  242.   convertDate: function(strDate){
  243.     strDate=strDate.substring(5);
  244.     var sections=strDate.split(" ");
  245.     var day=sections[0];
  246.     var monthStr=sections[1];
  247.     var months=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
  248.     var month=months.indexOf(monthStr);
  249.     var year=sections[2];
  250.     var arrTime=null;
  251.     if (sections.length>=3)
  252.       arrTime=sections[3].split(":");
  253.  
  254.     var date=new Date();
  255.     date.setFullYear(year,month,day);
  256.     if (arrTime)
  257.       date.setHours(parseInt(arrTime[0]),parseInt(arrTime[1])),parseInt(arrTime[2]);
  258.     return date;
  259.   },
  260.   /*
  261.    * Downloads the bookmark xml feed from Google and calls the command passed in (action)
  262.    * There are so many try and catches because I got fed up with people complaining of all these obscure errors.
  263.    */
  264.   getBookmarksFeed: function(action,sidebar,start,num){
  265.     this.recievedBookmarks=1;
  266.     var prefs = Components.classes["@mozilla.org/preferences-service;1"].
  267.     getService(Components.interfaces.nsIPrefService).
  268.     getBranch("gmarks");
  269.     var validate=this.GMS.validateFavs;
  270.     var invalidlbls=prefs.getCharPref(".invalidlbls");
  271.     var invalid=invalidlbls.split(/,\s*/);
  272.     start=start?start:0;
  273.     num=num?num:1000;
  274.     var dom;//Bookmark info
  275.     this.GMS.isSignedIn = this.GMS.checkSignedCookie();
  276.     debug("GMarks isSignedIn="+this.GMS.isSignedIn+"\n");
  277.     var auto=prefs.getBoolPref(".signin");
  278.     if (auto && !this.GMS.isSignedIn){
  279.       var pass=this.GMS.getPassInfo();
  280.       if (pass){
  281.         this.onSignIn(false,pass.user,pass.password,action,sidebar,start,num);
  282.       }
  283.     }
  284.     else if (!this.GMS.isSignedIn){
  285.       this.GMS.recievedBookmarks=0;
  286.       this.GMS.doCommand('onrefresh');
  287.       return;
  288.     }
  289.     if (!action) action = "onrefresh";
  290.     var com=this;
  291.  
  292.     if (com.GMS.isSignedIn){
  293.       com.GMS.sortBy = prefs.getCharPref("sortby");
  294.       com.GMS.loading=true;
  295.       var loadFreq=(com.GMS.sortBy=="freq" || com.GMS.showFreq==true);
  296.       var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
  297.         .createInstance(Components.interfaces.nsIXMLHttpRequest);
  298.       req.open("GET", "https://www.google.com/bookmarks/lookup?output=rss&sort="+
  299.       com.GMS.sortBy+"&start="+start+"&num="+num, true);
  300.       req.send(null);
  301.       debug("GMarks RSS: Connecting... \n");
  302.       req.onreadystatechange = function(ev){
  303.         if(req.readyState == 4){
  304.           var status = -1;
  305.           try {status = req.status} catch(e){};
  306.           if(status == 200){
  307.             if ((dom = req.responseXML)){
  308.               //<smh:signature>siggoeshere</smh:signature>
  309.               var sigs=dom.documentElement.getElementsByTagName("signature");
  310.               if (sigs.length==0) sigs=dom.documentElement.getElementsByTagName("smh:signature");
  311.               if (sigs.length==0) sigs=dom.documentElement.getElementsByTagNameNS("smh","signature");
  312.               if (sigs.length>0)
  313.                 com.signature=sigs[0].firstChild.nodeValue;
  314.               var items = dom.documentElement.getElementsByTagName('item');
  315.               if (start==0) com.GMS.bookmarkArray=new Array();
  316.               var i=0;
  317.               var badApples=0;
  318.               var startindex = com.GMS.bookmarkArray.length;
  319.               var recentDate=0;
  320.               var freqMin=0;
  321.               if (start==0){
  322.                 com.GMS.recent=new Array();
  323.                 com.GMS.frequent=new Array();
  324.               }
  325.               else{
  326.                 if (com.GMS.recent.length>0) recentDate=com.GMS.recent[com.GMS.recent.length-1];
  327.                 if (com.GMS.frequent.length>0) frequentDate=com.GMS.frequent[com.GMS.frequent.length-1];
  328.               }
  329.               //For getting the visit count info
  330.               var RDF, HISTDS=null;
  331.               if (!Components.classes["@mozilla.org/browser/nav-history-service;1"]){
  332.                 RDF = Components.classes["@mozilla.org/rdf/rdf-service;1"]
  333.                   .getService(Components.interfaces.nsIRDFService);
  334.                 try{
  335.                   HISTDS  = RDF.GetDataSource("rdf:history");
  336.                 }
  337.                 catch(e){loadFreq=false;}
  338.               }
  339.  
  340.               for (i = 0; i<items.length; i=i+1) {
  341.                 var newbkmk;
  342.                 try{
  343.                   newbkmk=com.getBookmarkFromRSS(items[i],loadFreq,RDF,HISTDS);
  344.                   var tIndex=i+startindex-badApples;
  345.                   if (i>0 && com.GMS.sortBy!="date"){
  346.                     tIndex=com.GMS.addBookmark(newbkmk);
  347.                   }
  348.                   else {
  349.                     com.GMS.bookmarkArray[tIndex]=newbkmk;
  350.                     com.GMS.updateRecent(newbkmk);
  351.                   }
  352.                   if (com.GMS.showFavs && (com.GMS.sortBy=="date" || !com.GMS.validateFavs)){
  353.                     com.GMS.getImage(tIndex,0);
  354.                   }
  355.                 }
  356.                 catch(e){
  357.                   badApples++;
  358.                   debug("Error with bookmark\n",true);
  359.                   debug(e+"\n",true);
  360.                   debug("stack: "+e.stack+"\n",true);
  361.                   debug("Title: "+newbkmk.title+"\n",true);
  362.                   debug("URL: "+newbkmk.url+"\n",true);
  363.                   debug("Labels: "+newbkmk.labels+"\n",true);
  364.                   debug("ID: "+newbkmk.id+"\n",true);
  365.                   debug("Date: "+newbkmk.date+"\n",true);
  366.                 }
  367.               }
  368.             }
  369.             if (badApples>0)    debug("GMarks: number of bad bookmarks = "+badApples+"\n");
  370.             if (items.length==num){
  371.               com.getBookmarksFeed(action,sidebar,start+1000,num);
  372.             }
  373.             else{
  374.               if (com.GMS.sortBy!="date"){
  375.                 if (com.GMS.showFavs && com.GMS.validateFavs){
  376.                   //This is done after already looping because doing it in the first loop
  377.                   //would result in a different index. It would then need to search
  378.                   //the array each time it gets a favicon response
  379.                   for (var i=0;i<com.GMS.bookmarkArray.length;i++)
  380.                     com.GMS.getImage(i,0);
  381.                 }
  382.               }
  383.               if (com.GMS.readerLabel.length==0){
  384.                 com.GMS.recievedBookmarks=2;
  385.                 com.GMS.loading=false;
  386.                 com.GMS.doCommand(action);
  387.               }
  388.               else{
  389.                 com.GMS.getReaderStars(action);
  390.               }
  391.             }
  392.  
  393.           }
  394.           else{
  395.             //Problem loading!
  396.             com.GMS.loading=false;
  397.             com.GMS.isSignedIn=false;
  398.             com.GMS.recievedBookmarks=0;
  399.             com.GMS.doCommand("onload");
  400.             dump("Bookmark connection error\n");
  401.           }
  402.         }
  403.       }
  404.     }//else if (sidebar) this.doCommand(action);
  405.   },
  406.   /*
  407.    * Same as the getBookmarksFeed, but returns only those which fit the query
  408.    */
  409.   getSiteSearch: function(query, action, sidebar){
  410.     var com=this;
  411.     var prefs = Components.classes["@mozilla.org/preferences-service;1"].
  412.               getService(Components.interfaces.nsIPrefService).getBranch("gmarks");
  413.     var validate=com.GMS.validateFavs;
  414.     var invalidlbls=prefs.getCharPref(".invalidlbls");
  415.     var invalid=invalidlbls.split(/,\s*/);
  416.     var dom;//Bookmark info
  417.     this.GMS.isSignedIn = this.checkSignedCookie();
  418.     var auto=prefs.getBoolPref(".signin");
  419.     if (auto && !this.GMS.isSignedIn){
  420.       var pass=this.GMS.getPassInfo();
  421.       if (pass) this.onSignIn(false,pass.user,pass.password);
  422.     }
  423.  
  424.     if (com.GMS.isSignedIn){
  425.       com.GMS.sortBy = prefs.getCharPref("sortby");
  426.       com.GMS.loading=true;
  427.       var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
  428.            .createInstance(Components.interfaces.nsIXMLHttpRequest);
  429.  
  430.       // Asyncronous connection with Google Bookmarks server
  431.       req.open("GET", "https://www.google.com/bookmarks/find?start=0&bkmk=1&output=rss&num=10000&q="+query, true);
  432.       req.send(null);
  433.       debug("Search RSS: Connecting... \n");
  434.       req.onreadystatechange = function(ev){
  435.         if(req.readyState == 4)
  436.         {
  437.           var status = -1;
  438.           try {status = req.status} catch(e) {
  439.             dump("error getting the status\n");
  440.           }
  441.  
  442.           if(status == 200){
  443.             debug("Search RSS: Connection worked! ("+req.status+")\n")
  444.             if ((dom = req.responseXML))
  445.             {
  446.               var items = dom.documentElement.getElementsByTagName('item');
  447.               com.GMS.searchArray=new Array(items.length);
  448.               var i=0;
  449.               for (i = 0; i<items.length; i=i+1) {
  450.                 var newbkmk=com.getBookmarkFromRSS(items[i],false);
  451.                 com.GMS.searchArray[i]=newbkmk;
  452.                 if (com.GMS.showFavs){
  453.                   com.GMS.getImage(i,1);
  454.                 }
  455.               }
  456.               debug("RSS Items: "+com.GMS.searchArray.length+"\n");
  457.               com.GMS.loading=false;
  458.               com.GMS.doCommand(action);
  459.             }
  460.           }
  461.         }
  462.       }
  463.     }else if (sidebar) {com.GMS.loading=false; com.GMS.doCommand(action);}
  464.   },
  465.   getBookmarkFromRSS: function(xml,loadFreq,RDF,HISTDS){
  466.     var auxBookmark = this.GMS.createNewBookmark();
  467.     auxBookmark.labels = new Array();
  468.  
  469.     var eleArr;
  470.     try{
  471.       //For FF2
  472.       eleArr=xml.getElementsByTagName('bkmk_id');
  473.       //For FF3
  474.       if (eleArr==null || eleArr.length==0) eleArr=xml.getElementsByTagName("smh:bkmk_id");
  475.       if (eleArr==null || eleArr.length==0) eleArr=xml.getElementsByTagNameNS("smh","bkmk_id");
  476.       if (eleArr!=null)
  477.         auxBookmark.id = eleArr[0].childNodes[0].nodeValue;
  478.       else
  479.         auxBookmark.id = 0;
  480.     }
  481.     catch(e){
  482.       auxBookmark.id = 0;
  483.       debug("GMarks - id error\n"+e+"\n",true);
  484.     }
  485.     try{
  486.       var links=xml.getElementsByTagName('link');
  487.       if (links.length>0 && links[0].childNodes.length>0){
  488.         auxBookmark.url=links[0].childNodes[0].nodeValue;
  489.       }
  490.       else
  491.         auxBookmark.url="about:blank";
  492.     }
  493.     catch(e){
  494.       auxBookmark.url = "about:blank";
  495.       debug("GMarks - url error\n"+e+"\n",true);
  496.     }
  497.     try{
  498.       //For FF2
  499.       eleArr=xml.getElementsByTagName('bkmk_title');
  500.       //For FF3
  501.       if (eleArr==null || eleArr.length==0) eleArr=xml.getElementsByTagName("smh:bkmk_title");
  502.       if (eleArr==null || eleArr.length==0) eleArr=xml.getElementsByTagNameNS("smh","bkmk_title");
  503.       var tag=eleArr;
  504.       if (tag!=null && tag.length>0)
  505.         auxBookmark.title = tag[0].childNodes[0].nodeValue;
  506.       else
  507.         auxBookmark.title = auxBookmark.url;
  508.     }
  509.     catch(e){
  510.       auxBookmark.title = auxBookmark.url;
  511.       debug("GMarks - title error\n"+e+"\n",true);
  512.     }
  513.     /*
  514.     var RDF = Components.classes["@mozilla.org/rdf/rdf-service;1"] .getService(Components.interfaces.nsIRDFService); var HISTDS = RDF.GetDataSource("rdf:history"); var kRDFLITIID = Components.interfaces.nsIRDFLiteral; var kRDFINTIID = Components.interfaces.nsIRDFInt; var NC_NS = "http://home.netscape.this/NC-rdf#"; var aURL="http://google.com"; var rSource = RDF.GetResource(aURL); var nameArc = RDF.GetResource(NC_NS+"Name"); var urlArc = RDF.GetResource(NC_NS+"URL"); var visitArc = RDF.GetResource(NC_NS+"VisitCount"); var rName = HISTDS.GetTarget(rSource, visitArc, true); var visits = rName ? rName.QueryInterface(kRDFINTIID).Value : -1; print("visits: "+visits);
  515.      */
  516.     if (loadFreq){
  517.       try{
  518.         auxBookmark.freq=this.GMS.getBookmarkVisits(auxBookmark.url,RDF,HISTDS);
  519.  
  520.         //See if its one of the 10 most frequent bookmarks.
  521.         if (this.GMS.frequent.length<10 || auxBookmark.freq>freqMin){
  522.           var addedbkmk=this.GMS.updateFrequent(auxBookmark);
  523.           if (addedbkmk){
  524.             freqMin=this.GMS.frequent[this.GMS.frequent.length-1].freq;
  525.           }
  526.         }
  527.       }
  528.       catch(e){
  529.         dump("History access error\n"+e+"\n",true);
  530.       }
  531.     }
  532.     try{
  533.       auxBookmark.date = this.convertDate(xml.getElementsByTagName('pubDate')[0].childNodes[0].nodeValue);
  534.       //this.GMS.updateRecent(auxBookmark);
  535.     }
  536.     catch(e){
  537.       auxBookmark.date = new Date();
  538.       debug("GMarks - date error\n"+e+"\n",true);
  539.     }
  540.     try{
  541.       //For FF2
  542.       eleArr=xml.getElementsByTagName('bkmk_annotation');
  543.       //For FF3
  544.       if (eleArr==null || eleArr.length==0)
  545.         eleArr=xml.getElementsByTagName("smh:bkmk_annotation");
  546.       if (eleArr==null || eleArr.length==0)
  547.         eleArr=xml.getElementsByTagNameNS("smh","bkmk_annotation");
  548.       var notesNode=eleArr;
  549.       if (notesNode!=null && notesNode.length>0){
  550.         auxBookmark.notes=notesNode[0].childNodes[0].nodeValue;
  551.         auxBookmark.notes=decodeURIComponent(auxBookmark.notes);
  552.       }
  553.       else
  554.         auxBookmark.notes = "";
  555.     }
  556.     catch(e){
  557.       auxBookmark.notes = "";
  558.       debug("GMarks - notes error\n"+e+"\n",true);
  559.     }
  560.     try{
  561.       //For FF2
  562.       eleArr=xml.getElementsByTagName('bkmk_label');
  563.       //For FF3
  564.       if (eleArr==null || eleArr.length==0)
  565.         eleArr=xml.getElementsByTagName("smh:bkmk_label");
  566.       if (eleArr==null || eleArr.length==0)
  567.         eleArr=xml.getElementsByTagNameNS("smh","bkmk_label");
  568.       var auxLabelsArray = eleArr;
  569.       for (var j = 0; j < auxLabelsArray.length; j++){
  570.           auxBookmark.labels.push(auxLabelsArray[j].childNodes[0].nodeValue);
  571.       }
  572.     }
  573.     catch(e){
  574.       debug("GMarks - label error\n"+e+"\n",true);
  575.     }
  576.     /*
  577.      * If it should be a bookmark, put the javascript: link in the url field
  578.      * GMarks puts it in the notes field because Google insists on stripping it out.
  579.      */
  580.     if (auxBookmark.url.indexOf(this.BKMKLET_URL)>-1 ||
  581.         auxBookmark.url.indexOf(this.OLD_BKMKLET_URL)>-1){
  582.       auxBookmark.url=auxBookmark.notes;
  583.       auxBookmark.notes="";
  584.     }
  585.  
  586.     return auxBookmark;
  587.   },
  588.   /*
  589.    * Retrieves the starred items from Google Reader
  590.    * This is not called by default, there is an option to turn this on.
  591.    */
  592.   getReaderStars : function(action){
  593.     var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
  594.            .createInstance(Components.interfaces.nsIXMLHttpRequest);
  595.     var userId="-";
  596.     var num=1000;
  597.     var validate=this.GMS.validateFavs;
  598.     this.GMS.loading=true;
  599.     req.open("GET", "https://www.google.com/reader/atom/user/"+userId+"/state/com.google/starred?n="+num+"&ck="+userId, true);
  600.     req.send(null);
  601.     debug("GReader XML: Connecting... \n");
  602.     var com=this;
  603.     req.onreadystatechange = function(ev){
  604.       if(req.readyState == 4)
  605.       {
  606.         var status = -1;
  607.         try {status = req.status} catch(e) {}
  608.         if(status == 200){
  609.           if ((dom = req.responseXML))
  610.           {
  611.             var items = dom.documentElement.getElementsByTagName('entry');
  612.             var i=0;
  613.             for (i = 0; i<items.length; i++) {
  614.               var auxBookmark;
  615.               try{
  616.                 auxBookmark = com.GMS.createNewBookmark();
  617.                 auxBookmark.id=1;
  618.                 auxBookmark.serv="GReader";
  619.                 try{
  620.                   var categories=items[i].getElementsByTagName('category');
  621.                   for (var j=0;j<categories.length;j++){
  622.                     var term=categories[j].getAttribute('term');
  623.                     var pos
  624.                     var prefix='user/'+userId+'/label/';
  625.                     if ((pos=term.indexOf(prefix))!=-1){
  626.                       auxBookmark.labels.push(term.substring(pos+prefix.length));
  627.                     }
  628.                   }
  629.                 }
  630.                 catch(e){
  631.                   debug("error getting categories\n");
  632.                 }
  633.                 auxBookmark.labels.push(com.GMS.readerLabel);
  634.                 try{
  635.                   auxBookmark.url =   items[i].getElementsByTagName('id')[0].getAttribute('gr:original-id');
  636.                 }
  637.                 catch(e){
  638.                   auxBookmark.url = "about:blank";
  639.                   debug("GReader - url error\n");
  640.                 }
  641.                 try{
  642.                   var tag=items[i].getElementsByTagName('title');
  643.                   if (tag.length>0){
  644.                     auxBookmark.title = tag[0].childNodes[0].nodeValue;
  645.                     auxBookmark.title=auxBookmark.title.replace('"','"');
  646.                   }
  647.                   else
  648.                     auxBookmark.title = auxBookmark.url;
  649.                 }
  650.                 catch(e){
  651.                   auxBookmark.title = auxBookmark.url;
  652.                   debug("GReader - title error\n");
  653.                 }
  654.                 try{
  655.                   auxBookmark.date =   new Date(items[i].getAttribute('gr:crawl-timestamp-msec'));
  656.                 }
  657.                 catch(e){
  658.                   auxBookmark.date = 0;
  659.                   debug("GReader - date error\n");
  660.                 }
  661.                 var idx=com.GMS.updateBookmark(auxBookmark,false,null,true);
  662.                 if (com.GMS.showFavs){
  663.                   com.GMS.getImage(idx,0);
  664.                 }
  665.               }
  666.               catch(e){
  667.                 debug('error loading reader item\n');
  668.               }
  669.             }
  670.           }
  671.           com.GMS.recievedBookmarks=2;
  672.         }
  673.         else{
  674.           com.GMS.recievedBookmarks=0;
  675.         }
  676.  
  677.         com.GMS.loading=false;
  678.         if (action.length>0){
  679.           com.GMS.doCommand(action);
  680.         }
  681.       }
  682.     }
  683.   },
  684.   /*
  685.    * Gets the id of the last added bookmark so it can be removed during the current session.
  686.    */
  687.   getIDs : function(i,time,bkmks){
  688.  
  689.     var dom;//Bookmark info
  690.     this.GMS.isSignedIn = this.checkSignedCookie();
  691.     var com=this;
  692.     if (this.GMS.isSignedIn){
  693.       var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
  694.            .createInstance(Components.interfaces.nsIXMLHttpRequest);
  695.  
  696.        //&all=1
  697.        //Math.floor(time*999.996780335)
  698.        //dump("time: "+new Date(time)+"\n");
  699.       req.open("GET", "https://www.google.com/bookmarks/lookup?output=xml&num=30&min="+Math.floor(time*999.996780335), true);
  700.       // req.open("GET", "http://www.google.com/bookmarks/lookup?output=xml&num=2000&min="+Math.floor(time*999), true);
  701.       //req.open("GET", "http://www.google.com/bookmarks/lookup?output=xml&sort=date&num="+i, true);
  702.       req.send(null);
  703.       req.onreadystatechange = function(ev){
  704.         if(req.readyState == 4) {
  705.           var status = -1;
  706.           try {status = req.status} catch(e) {
  707.             dump("error getting the status2\n");
  708.           }
  709.           if(status == 200){
  710.             if ((dom = req.responseXML)){
  711.               var items = dom.documentElement.getElementsByTagName('bookmark');
  712.               //dump("bookmarks: "+items.length+" i: "+i+"\n");
  713.               //com.GMS.bookmarkArray=new Array(items.length);
  714.               var i=0;
  715.               var badApples=0;
  716.               var RDF, HISTDS;
  717.               RDF= Components.classes["@mozilla.org/rdf/rdf-service;1"]
  718.                 .getService(Components.interfaces.nsIRDFService);
  719.               try{
  720.                 HISTDS  = RDF.GetDataSource("rdf:history");
  721.               }
  722.               catch(e){}
  723.               for (i = 0; i<items.length; i=i+1) {
  724.                 var tmpBkmk = com.GMS.createNewBookmark();
  725.                 var item = items[i];
  726.                 try{
  727.                   tmpBkmk.id =    item.getElementsByTagName('id')[0].childNodes[0].nodeValue;
  728.                   tmpBkmk.url =   item.getElementsByTagName('url')[0].childNodes[0].nodeValue;
  729.                   var titlenode = item.getElementsByTagName('title');
  730.                   if (titlenode.length>0 && titlenode[0].childNodes.length>0)
  731.                     tmpBkmk.title = titlenode[0].childNodes[0].nodeValue;
  732.                   var date=item.getElementsByTagName('timestamp')[0].childNodes[0].nodeValue;
  733.                   tmpBkmk.freq=com.GMS.getBookmarkVisits(tmpBkmk,RDF,HISTDS);
  734.                   tmpBkmk.date =  new Date(date/1000);
  735.                   //dump("date: "+date+"\n");
  736.                   //dump(tmpBkmk.date+"\n");
  737.  
  738.                   //tmpBkmk.setTime(item.getElementsByTagName('timestamp')[0].childNodes[0].nodeValue);
  739.                   var idx=com.GMS.getBookmarkIndex(tmpBkmk);
  740.                   if (idx<0)
  741.                     idx=com.GMS.isBookmarked(tmpBkmk);
  742.                   if (idx>=0 && idx!=false){
  743.                     com.GMS.bookmarkArray[idx].id=tmpBkmk.id;
  744.                   }
  745.                   else{
  746.                     debug("Could not find bookmark with GETID("+idx+")\n",true);
  747.                     debug("Title: "+tmpBkmk.title+"\n",true);
  748.                     debug("Url: "+tmpBkmk.url+"\n",true);
  749.                     debug("ID: "+tmpBkmk.id+"\n",true);
  750.                     debug("Date: "+tmpBkmk.date+"\n",true);
  751.                   }
  752.  
  753.                 }
  754.                 catch(e){
  755.                   debug("Error with bookmark\n",true);
  756.                   debug(e+"\n",true);
  757.                 }
  758.               }
  759.             }
  760.           }
  761.           else{
  762.             debug("error getting the new id",true);
  763.           }
  764.         }
  765.       }
  766.     }
  767.   },
  768.   getID : function(bm){
  769.     var dom;//Bookmark info
  770.     this.GMS.isSignedIn = this.checkSignedCookie();
  771.     var com=this;
  772.     if (this.isSignedIn){
  773.       var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
  774.            .createInstance(Components.interfaces.nsIXMLHttpRequest);
  775.  
  776.       req.open("GET", "https://www.google.com/bookmarks/lookup?output=xml&sort=date&num=1", true);
  777.       req.send(null);
  778.       req.onreadystatechange = function(ev){
  779.         if(req.readyState == 4) {
  780.           var status = -1;
  781.           try {status = req.status} catch(e) {
  782.             dump("error getting the status2\n");
  783.           }
  784.           if(status == 200){
  785.             if ((dom = req.responseXML)){
  786.               var item = dom.documentElement.getElementsByTagName('bookmark')[0];
  787.               var tmpBkmk={id: 0, url: null, title: null, labels: new Array(), notes: "", date: 0, image: null};//createNewBookmark();
  788.               tmpBkmk.id =    item.getElementsByTagName('id')[0].childNodes[0].nodeValue;
  789.               tmpBkmk.url =   item.getElementsByTagName('url')[0].childNodes[0].nodeValue;
  790.               tmpBkmk.date =  item.getElementsByTagName('timestamp')[0].childNodes[0].nodeValue;
  791.               tmpBkmk.labels=new Array();
  792.               var tag=item.getElementsByTagName('title');
  793.               if (tag.length>0)
  794.                 tmpBkmk.title = tag[0].childNodes[0].nodeValue;
  795.               else
  796.                 tmpBkmk.title = tmpBkmk.url;
  797.  
  798.               var idx=cin.GMS.getBookmarkIndex(tmpBkmk);
  799.               if (idx>=0){
  800.                 debug("Found ID for "+com.GMS.bookmarkArray[idx].title +" | "+com.GMS.bookmarkArray[idx].url+"\n");
  801.                 com.GMS.bookmarkArray[idx].id=tmpBkmk.id;;
  802.                 if (!com.GMS.validateFavs && com.GMS.showFavs){
  803.                   try{
  804.                     this.bookmarkArray[idx].image=this.getIcon(this.bookmarkArray[idx].url).spec;
  805.                   }
  806.                   catch(e){}
  807.                 }
  808.                 com.GMS.doCommand("quickrefresh");
  809.               }
  810.               else{
  811.                 debug("Could not find bookmark with GETID\n",true);
  812.               }
  813.             }
  814.           }
  815.           else
  816.             debug("error getting the new id",true);
  817.         }
  818.       }
  819.     }
  820.   },
  821.   //Required
  822.   QueryInterface: function(iid) {
  823.     if (!iid.equals(Components.interfaces.nsISupports) &&
  824.       !iid.equals(GMARKS_COM_IID))
  825.       throw Components.results.NS_ERROR_NO_INTERFACE;
  826.     return this;
  827.   }
  828. }
  829. function debug(msg,force){
  830.   if (force){
  831.     dump(msg);
  832.   }
  833.   else{
  834.     //dump(msg);
  835.   }
  836. }
  837. var nsGMarksComModule = {
  838.   registerSelf: function(compMgr, fileSpec, location, type) {
  839.     compMgr =
  840.     compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  841.     compMgr.registerFactoryLocation(GMARKS_COM_CID,
  842.                     "GMarks Com",
  843.                     GMARKS_COM_CONTRACTID,
  844.                     fileSpec,
  845.                     location,
  846.                     type);
  847.   },
  848.   unregisterSelf: function(aCompMgr, aLocation, aType)
  849.   {
  850.     aCompMgr = aCompMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  851.     aCompMgr.unregisterFactoryLocation(GMARKS_COM_CID, aLocation);
  852.   },
  853.   getClassObject: function(compMgr, cid, iid) {
  854.     if (!cid.equals(GMARKS_COM_CID))
  855.       throw Components.results.NS_ERROR_NO_INTERFACE;
  856.     if (!iid.equals(Components.interfaces.nsIFactory))
  857.       throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  858.     return nsGMarksComFactory;
  859.   },
  860.   canUnload: function(compMgr) { return true; }
  861. };
  862. var nsGMarksComFactory = {
  863.   singleton: null,
  864.   createInstance: function (aOuter, aIID)
  865.   {
  866.   if (aOuter != null)
  867.     throw Components.results.NS_ERROR_NO_AGGREGATION;
  868.   if (this.singleton == null)
  869.     this.singleton = new nsGMarksCom();
  870.   return this.singleton.QueryInterface(aIID);
  871.   }
  872. };
  873. function NSGetModule(comMgr, fileSpec) { return nsGMarksComModule; }
  874.